<?php
// 邮箱发送
Vendor ( 'PHPMailer.class#phpmailer' );

// +-----------------------------------
// 判断字符串是不是空的
// return :boolean
// +-----------------------------------
function util_isEmptyString($data/*String*/){
	if (! is_string ( $data ))
		return true; // 判断是否是字符串类型
	if (empty ( $data ))
		return true; // 判断是否已定义字符串
	if ($data == '')
		return true; // 判断字符串是否为空
	return false;
}

// +----------------------------------------
// 向邮箱发送邮件
// return boolean
// +----------------------------------------
function util_send_mail($title = ''/*标题*/, $content = ''/*内容*/,$email = ''/*收件人邮箱*/,$isHtml = true/*是否以HTML格式发送*/){
	$mail = new PHPMailer (); // 建立邮件发送类
	$mail->IsSMTP (); // 使用SMTP方式发送
	$mail->Host = "smtp.163.com"; // 您的企业邮局域名
	$mail->SMTPAuth = true; // 启用SMTP验证功能
	$mail->Username = "wteamweb@163.com"; // 发送方邮件地址(请填写完整的email地址)
	$mail->Password = "wteamweb2011"; // 发送放邮件密码
	$mail->Port = 25;
	$mail->From = "wteamweb@163.com"; // 发送方邮件地址
	$mail->FromName = "天天爱购物";
	$mail->AddAddress ( $email, "天天爱购物" ); // 收件人地址，可以替换成任何想要接收邮件的email信箱,格式是AddAddress("收件人email","收件人姓名")
	                                       // $mail->AddReplyTo("", "");
	                                       // $mail->AddAttachment("/var/tmp/file.tar.gz"); // 添加附件
	$mail->IsHTML ( true ); // set email format to HTML //是否使用HTML格式
	$mail->CharSet = "utf-8";
	$mail->Subject = "$title"; // 邮件标题
	$mail->Body = $content; // 邮件内容
	$mail->AltBody = "This is the body in plain text for non-HTML mail clients"; // 附加信息，可以省略
	
	if (! $mail->Send ()) {
		// return $mail->ErrorInfo;
		return false;
	} else {
		return true;
	}
}

// +---------------------------------------------
// 获取一定范围内的随机数
// return String
// +---------------------------------------------
function util_rand_number($min = 1000, $max = 10000) {
	return sprintf ( "%0" . strlen ( $max ) . "d", mt_rand ( $min, $max ) );
}

/*
 * -----------------------------------------------/ 说明：判断字符串是否符合电话号码格式 返回：int 1（符合）0（不符合） 例子：-- 参数： phone：电话号码[String] /-------------------------------------------------
 */
function util_isPhone($phone) {
	if (preg_match ( "/1[3458]{1}\d{9}$/", $phone )) {
		return 1;
	} else {
		return 0;
	}
}

/*
 * -----------------------------------------------/ 
 * 说明：发送手机验证码，如果发送成功返回验证码，否则返回0 返回：string 例子：-- 参数： 
 * sendPhone：需要发送的电话号码[string] content：发送的内容[string] /-------------------------------------------------
 */
function util_send_phone_code($sendPhone = "", $content = "") {
	$data = util_get_phone_code ( $sendPhone );
	if ($data) {
		if ($data ['total'] <= 4) {
			$Uid = URLEncode ( '云劭科技-海说' );
			$Key = '27b80985e22c05a309a0';
			$mob = $sendPhone;
			$random = mt_rand ( 1000, 9999 );
			$mobtxt = URLEncode ( $content . "  海说验证码：" . $random . "  打死都不能告诉别人哦！" );
			$url = 'http://utf8.sms.webchinese.cn/?Uid=' . $Uid . '&Key=' . $Key . '&smsMob=' . $mob . '&smsText=' . $mobtxt;
			
			if (function_exists ( 'file_get_contents' )) {
				$file_contents = file_get_contents ( $url );
			} else {
				$ch = curl_init ();
				$timeout = 5;
				curl_setopt ( $ch, CURLOPT_URL, $url );
				curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
				curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
				$file_contents = curl_exec ( $ch );
				curl_close ( $ch );
			}
			if ($file_contents < 0) {
				return 0;
			} else {
				util_code_save ( $sendPhone, $random );
				return $random;
			}
		}else {
			return 2;
		}
	} else {
		$Uid = URLEncode ( '云劭科技-海说' );
		$Key = '27b80985e22c05a309a0';
		$mob = $sendPhone;
		$random = mt_rand ( 1000, 9999 );
		$mobtxt = URLEncode ( $content . "  海说验证码：" . $random . "  打死都不能告诉别人哦！" );
		$url = 'http://utf8.sms.webchinese.cn/?Uid=' . $Uid . '&Key=' . $Key . '&smsMob=' . $mob . '&smsText=' . $mobtxt;
			
		if (function_exists ( 'file_get_contents' )) {
			$file_contents = file_get_contents ( $url );
		} else {
			$ch = curl_init ();
			$timeout = 5;
			curl_setopt ( $ch, CURLOPT_URL, $url );
			curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
			curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
			$file_contents = curl_exec ( $ch );
			curl_close ( $ch );
		}
		if ($file_contents < 0) {
			return 0;
		} else {
			util_code_save ( $sendPhone, $random );
			return $random;
		}
	}	
}

// +---------------------------------------------
// 保存验证码
// 参数：$sendPhone:手机号，$random：验证码
// return String 如果返回“0”,表示没有
// +---------------------------------------------
function util_code_save($sendPhone, $random, $flush = FALSE) {
	if ($flush) { // 清零
		$data = S ( 'user_code' . $sendPhone );
		$data ['total'] = 0;
		$data ['sendPhone'] = $sendPhone;
		$data ['random'] = $random;
		S ( 'user_code' . $sendPhone, $data );
		return;
	}

	// 内存数据已存在时，相应数据+1
	if (S ( 'user_code' . $sendPhone )) {
		$data = S ( 'user_code' . $sendPhone );
		$data ['total'] ++;
		$data ['sendPhone'] = $sendPhone;
		$data ['random'] = $random;
		S ( 'user_code' . $sendPhone, $data, 3600 );
		// 内存数据不存在时，初始化用户数据并写入到内存
	} else {
		$data = array (
				'total' => 0,
				'sendPhone' => 0 ,
				'random' => 0,
		);
		$data ['total'] ++;
		$data ['sendPhone'] = $sendPhone;
		$data ['random'] = $random;
		S ( 'user_code' . $sendPhone, $data, 3600 );
	}
}
// +---------------------------------------------
// 获取验证码
// return String 如果返回“0”,表示没有
// +---------------------------------------------
function util_get_phone_code($sendPhone) {
	$data = S ( 'user_code' . $sendPhone );
	if ($data) {
		return (string)$data['random'];
	} else {
		return 0;
	}
}

// +---------------------------------------------
// 检查验证码是否合法
// return true(真)　flase(假)
// +---------------------------------------------
function util_check_verify($code, $id = ''){
	$verify = new \Think\Verify();
	return $verify->check($code, $id);
}



/**
 * 往内存写入推送消息
 * [int] $uid [用户ID]
 * [int] $type [1：评论；2：私信；3：@用户 4:回复我的]
 * [boolen] $flush [是否清0]
 */
function set_msg($uid, $type, $flush = false) {
	$name = '';
	switch ($type) {
		case 1 :
			$name = 'comment';
			break;
		case 2 :
			$name = 'letter';
			break;
		case 3 :
			$name = 'atme';
			break;
		case 4 :
			$name = 'reply';
			break;
	}
	
	if ($flush) { // 查看了消息，清零
		$data = S ( 'usermsg' . $uid );
		$data [$name] ['total'] = 0;
		$data [$name] ['status'] = 0; // 1 没有推送 0已经推送
		S ( 'usermsg' . $uid, $data );
		return;
	}
	
	// 内存数据已存在时，相应数据+1
	if (S ( 'usermsg' . $uid )) {
		$data = S ( 'usermsg' . $uid );
		$data [$name] ['total'] ++;
		$data [$name] ['status'] = 1;
		S ( 'usermsg' . $uid, $data );
		// 内存数据不存在时，初始化用户数据并写入到内存
	} else {
		$data = array (
				'comment' => array (
						'total' => 0,
						'status' => 0 
				),
				'letter' => array (
						'total' => 0,
						'status' => 0 
				),
				'atme' => array (
						'total' => 0,
						'status' => 0 
				),
				'reply' => array (
						'total' => 0,
						'status' => 0 
				) 
		);
		$data [$name] ['total'] ++;
		$data [$name] ['status'] = 1;
		S ( 'usermsg' . $uid, $data );
	}
}

/**
 * 获取内存推送消息
 * [int] $uid [用户ID]
 */
function getMsg($uid) {
	$msg = S ( 'usermsg' . $uid );
	return $msg;
}

/*
 * @用户处理
 */
function atmeHandle($atwhos, $sendcardId) {
	// echo json_decode($atwhos);
	// die();
	// $preg = '/@(.*?)\s/i';
	// preg_match_all($preg, $content, $arr); //从content中取出@后面的username
	// dump($atwhos);
	$arr_atwho = explode ( ",", $atwhos );
	// dump($arr_atwho);
	if (! empty ( $arr_atwho )) {
		$db = M ( 'user' );
		$atme = M ( 'atme' );
		foreach ( $arr_atwho as $key => $v ) {
			// 找出和username匹配的id
			$uid = $db->where ( array (
					'nickname' => $v 
			) )->getField ( 'id' );
			if ($uid) {
				$data = array (
						'sendcardId' => $sendcardId,
						'userId' => $uid 
				);
				// 写入内存消息推送
				set_msg ( $uid, 3 );
				$atme->add ( $data );
			}
		}
	}
}

function  check_wap() {  
   $user_agent = $_SERVER['HTTP_USER_AGENT'];  
    $mobile_agents = Array("240x320","acer","acoon","acs-","abacho","ahong","airness","alcatel","amoi","android","anywhereyougo.com","applewebkit/525","applewebkit/532","asus","audio","au-mic","avantogo","becker","benq","bilbo","bird","blackberry","blazer","bleu","cdm-","compal","coolpad","danger","dbtel","dopod","elaine","eric","etouch","fly ","fly_","fly-","go.web","goodaccess","gradiente","grundig","haier","hedy","hitachi","htc","huawei","hutchison","inno","ipad","ipaq","ipod","jbrowser","kddi","kgt","kwc","lenovo","lg ","lg2","lg3","lg4","lg5","lg7","lg8","lg9","lg-","lge-","lge9","longcos","maemo","mercator","meridian","micromax","midp","mini","mitsu","mmm","mmp","mobi","mot-","moto","nec-","netfront","newgen","nexian","nf-browser","nintendo","nitro","nokia","nook","novarra","obigo","palm","panasonic","pantech","philips","phone","pg-","playstation","pocket","pt-","qc-","qtek","rover","sagem","sama","samu","sanyo","samsung","sch-","scooter","sec-","sendo","sgh-","sharp","siemens","sie-","softbank","sony","spice","sprint","spv","symbian","tablet","talkabout","tcl-","teleca","telit","tianyu","tim-","toshiba","tsm","up.browser","utec","utstar","verykool","virgin","vk-","voda","voxtel","vx","wap","wellco","wig browser","wii","windows ce","wireless","xda","xde","zte");  
    $is_mobile = false;  
    foreach ($mobile_agents as $device) {//这里把值遍历一遍，用于查找是否有上述字符串出现过  
       if (stristr($user_agent, $device)) { //stristr 查找访客端信息是否在上述数组中，不存在即为PC端。  
            $is_mobile = true;  
            break;  
        }  
    }  
    return $is_mobile;  
}  


function page($PageCount, $url, $pn)
{
	$pg = "";

	//写入页导航头部
	if ($pn != 1)
	{
		$pg .= "<a href=".$url."pn=1>[首页]</a>&nbsp;";
		$pg .= "<a href=".$url."pn=".($pn - 1).">[上一页]</a>&nbsp;";
	}
	else
	{
		$pg .= "[首页]&nbsp;";
		$pg .= "[上一页]&nbsp;";
	}

	//写入页导航中部

	if ($PageCount <= 10)//页数少于10
	{
		for ($i = 1; $i <= $PageCount; $i++)
		{
			if ($i != $pn)
			{
				$pg .= "<a href=".$url."pn=".$i.">[".$i."]</a>&nbsp;";
			}
			else
			{
				$pg .= $i."&nbsp;";
			}
		}
	}
	else//页数大于10
	{
		if ($pn <= 5)//进入前五页
		{
			for ($i = 1; $i <= 10; $i++)
			{
				if ($i != $pn)
				{
					$pg .= "<a href=".$url."pn=".$i.">[".$i."]</a>&nbsp;";
				}
				else
				{
					$pg .= $i."&nbsp;";
				}
			}
		}
		else if ($PageCount - $pn <= 5)//进入后五页
		{
			for ($i = $PageCount - 10; $i <= $PageCount; $i++)
			{
				if ($i != $pn)
				{
					$pg .= "<a href=".$url."pn=".$i.">[".$i."]</a>&nbsp;";
				}
				else
				{
					$pg .= $i."&nbsp;";
				}
			}
		}
		else//进入其他页
		{
			for ($i = $pn - 5; $i <= $pn + 5; $i++)
			{
				if ($i != $pn)
				{
					$pg .= "<a href=".$url."pn=".$i.">[".$i."]</a>&nbsp;";
				}
				else
				{
					$pg .= $i."&nbsp;";
				}
			}
		}
	}

	//写入页导航尾部
	if ($pn != $PageCount)
	{
		$pg .= "<a href=".$url."pn=".($pn + 1).">[下一页]</a>&nbsp;";
		$pg .= "<a href=".$url."pn=".$PageCount.">[尾页]</a>&nbsp;";
	}
	else
	{
		$pg .= "[下一页]&nbsp;";
		$pg .= "[尾页]&nbsp;";
	}

	$pg .= "&nbsp; &nbsp;共".$PageCount."页&nbsp;";
	$pg .= "<select name='select' onChange=javascript:window.location='".$url."pn='+this.options[this.selectedIndex].value;>";
	$pg .= "<option value=\"0\">请选择</option>";
	for ($i = 1; $i <= $PageCount; $i++)
	{
		$pg .= "<option value=".$i.">第".$i."页</option>";
	}
	$pg .= "</select>";

	return $pg;

}

/**
 * 邮件发送函数
 */
function sendMail($to, $title, $content) {
	Vendor('PHPMailer.PHPMailerAutoload');
// // 	vendor('phpmailer.class#phpmailer');
	$mail = new PHPMailer(); //实例化
// 	import('Vendor.PHPMailer.PHPMailer');
// 	$mail = new   \PHPMailer();
	$mail->IsSMTP(); // 启用SMTP
// 	$mail->SMTPDebug=1;
// 	$mail->Debugoutput = 'html';
	$mail->SMTPSecure = 'tls';
	$mail->Port = 587;
	$mail->Host=C('MAIL_HOST'); //smtp服务器的名称（这里以QQ邮箱为例）
	$mail->SMTPAuth = C('MAIL_SMTPAUTH'); //启用smtp认证
	$mail->Username = C('MAIL_USERNAME'); //你的邮箱名
	$mail->Password = C('MAIL_PASSWORD') ; //邮箱密码
	$mail->From = C('MAIL_FROM'); //发件人地址（也就是你的邮箱地址）
	$mail->FromName = C('MAIL_FROMNAME'); //发件人姓名
	$mail->AddAddress($to,"尊敬的客户");
	$mail->WordWrap = 50; //设置每行字符长度
	$mail->IsHTML(C('MAIL_ISHTML')); // 是否HTML格式邮件
	$mail->CharSet=C('MAIL_CHARSET'); //设置邮件编码
	$mail->Subject =$title; //邮件主题
	$mail->Body = $content; //邮件内容
	$mail->AltBody = $title; //邮件正文不支持HTML的备用显示
	if ($mail->Send()){
       return true;
     }else{
       return $mail->getMessage();
     }
}

function get_real_ip()
{
	$ip=false;
	if(!empty($_SERVER["HTTP_CLIENT_IP"]))
	{
		$ip = $_SERVER["HTTP_CLIENT_IP"];
	}
	if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
	{
		$ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
		if ($ip)
		{
			array_unshift($ips, $ip); $ip = FALSE;
		}
		for ($i = 0; $i < count($ips); $i++)
		{
		if (!eregi ("^(10|172\.16|192\.168)\.", $ips[$i]))
			{
				$ip = $ips[$i];
				break;
	}
	}
	}
return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}

//统计连续出现的'中'的当前连对和历史最大连对,'挂'当前连错和历史最大连错;
//参数1.中挂一维数组arr,2.要统的值
function series_num($arr,$str) {
// 	$arr = array('中','中','中','挂','挂','挂','中','中','中','挂','中','挂','中','挂','挂','挂','挂','挂','中');
// 	$str = '挂'; // 要统计的值
	$num = 0; // 当前连中长度
	$maxnum = 0; // 历史最大连中的长度
	for($i = 1; $i <count($arr); $i ++) {
		if ($arr [$i] == $str) {
			$num ++;//3
		} else {
			// 当前的数字与前面的不一样时
			if ($num > $maxnum) {//当前序列长度大于历史最长序列长度，则赋值给历史最长序列。
				$maxnum = $num;
			}
			$num = 0;
		}
	}
	$result['num']=$num;
	$result['maxnum']=$maxnum;
	return $result;
}

function get_order_str($len,$chars=NULL) {
	/* 选择一个随机的方案 */
	if (is_null($chars)){
		// 		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		// 		$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
	}
	mt_srand(10000000*(double)microtime());
	for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++){
		$str .= $chars[mt_rand(0, $lc)];
	}
	return $str;
}

//获取上个月月初时间戳和月末时间戳
function get_last_month_b_e_time(){
	
	$thismonth = date('m');
	$thisyear = date('Y');
	if ($thismonth == 1) {
		$lastmonth = 12;
		$lastyear = $thisyear - 1;
	} else {
		$lastmonth = $thismonth - 1;
		$lastyear = $thisyear;
	}
	$lastStartDay = $lastyear . '-' . $lastmonth . '-1';
	$lastEndDay = $lastyear . '-' . $lastmonth . '-' . date('t', strtotime($lastStartDay));
	$b_time = strtotime($lastStartDay);//上个月的月初时间戳
	$e_time = strtotime($lastEndDay);//上个月的月末时间戳
	
	$result['b_time'] = $b_time; 
	$result['e_time'] = $e_time;
	
	return $result;
}

//去掉重复user_id
function get_user_id_from_array($array,$id){
	$user_ids = array();
	foreach ($array as $key => $value) {
		array_push($user_ids, $value[$id]);
	}
	$user_ids=array_unique($user_ids);
	return $user_ids;
}

//通过user_id获取agent_id
function get_agent_id_by_user_id($user_id){
	$where['id']=$user_id;
	$user = D("User")->where($where)->field("id,agent_id")->find();
	return $user;
}

//获取提成比例
function get_rate($temp_money){
	if($temp_money>0&&$temp_money<=100){
		$rate=0.1;
	}else if($temp_money>100&&$temp_money<=500){
		$rate=0.2;
	}else if($temp_money>500&&$temp_money<=3000){
		$rate=0.3;
	}else if($temp_money>3000){
		$rate=0.4;
	}
	return $rate;
}

//今天是不是在号范围内
function is_in_day($star,$end){
	$day = intval(date('d',time()));
	if($day>=$star&&$day<=$end){
		return true;
	}else{
		return false;
	}
}






?>